<template>
  <div>
    <el-form :model="form" label-width="auto">
      <!--      <div v-if="showBackgroundColor">-->
      <!--        <p class="title">背景色</p>-->
      <!--        <el-form-item label="背景色">-->
      <!--          <el-color-picker v-model="form.backgroundColor" />-->
      <!--        </el-form-item>-->
      <!--      </div>-->

      <div class="component-style">
        <div class="header" @click="contentCollapsed = !contentCollapsed">
          <p class="title">内容间距</p>
          <el-icon v-if="!contentCollapsed"><ArrowDown /></el-icon>
          <el-icon v-else><ArrowRight /></el-icon>
        </div>
        <div v-if="!contentCollapsed">
          <el-form-item label="上边距：">
            <div class="flex">
              <el-slider style="width: 70%" :max="50" v-model="form.paddingTop" />
              <el-input
                type="number"
                style="width: 30%; margin-left: 20px"
                v-model.number="form.paddingTop"
              >
                <template #append>px</template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item label="下边距：" v-if="contentData.type === 'carousel'">
            <div class="flex">
              <el-slider style="width: 70%" :min="-100" :max="50" v-model="form.marginBottom" />
              <el-input
                type="number"
                style="width: 30%; margin-left: 20px"
                v-model.number="form.marginBottom"
              >
                <template #append>px</template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item label="下边距：" v-else>
            <div class="flex">
              <el-slider style="width: 70%" :max="50" v-model="form.paddingBottom" />
              <el-input
                type="number"
                style="width: 30%; margin-left: 20px"
                v-model.number="form.paddingBottom"
              >
                <template #append>px</template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item label="左右边距：">
            <div class="flex">
              <el-slider style="width: 70%" :max="50" v-model="form.paddingHorizontal" />
              <el-input
                type="number"
                style="width: 30%; margin-left: 20px"
                v-model.number="form.paddingHorizontal"
              >
                <template #append>px</template>
              </el-input>
            </div>
          </el-form-item>

          <template
            v-if="
              ['category_nav', 'info_card', 'goods', 'nav_title', 'nav_link', 'article'].includes(
                contentData.type
              )
            "
          >
            <el-form-item label="上圆角：">
              <div class="flex">
                <el-slider style="width: 70%" :max="50" v-model="form.topRadiusProxy" />
                <el-input
                  type="number"
                  style="width: 30%; margin-left: 20px"
                  v-model.number="form.topRadiusProxy"
                >
                  <template #append>px</template>
                </el-input>
              </div>
            </el-form-item>

            <el-form-item label="下圆角：">
              <div class="flex">
                <el-slider style="width: 70%" :max="50" v-model="form.bottomRadiusProxy" />
                <el-input
                  type="number"
                  style="width: 30%; margin-left: 20px"
                  v-model.number="form.bottomRadiusProxy"
                >
                  <template #append>px</template>
                </el-input>
              </div>
            </el-form-item>
          </template>

          <template v-else>
            <el-form-item label="圆角：">
              <div class="flex">
                <el-slider style="width: 70%" :max="50" v-model="form.borderRadius" />
                <el-input
                  type="number"
                  style="width: 30%; margin-left: 20px"
                  v-model.number="form.borderRadius"
                >
                  <template #append>px</template>
                </el-input>
              </div>
            </el-form-item>
          </template>

          <el-form-item
            label="背景色："
            v-if="!['carousel', 'img', 'empty_area', 'divider'].includes(contentData.type)"
          >
            <div style="display: flex; align-items: center">
              <el-color-picker v-model="form.backgroundColor" />
              <el-input style="width: 160px; margin-left: 10px" v-model="form.backgroundColor">
                <template #append>
                  <el-button @click="form.backgroundColor = '#f5f5f5'">重置</el-button>
                </template>
              </el-input>
            </div>
          </el-form-item>
        </div>
      </div>

      <!--      <div class="component-style">-->
      <!--        <div class="header" @click="componentCollapsed = !componentCollapsed">-->
      <!--          <p class="title">组件间距</p>-->
      <!--          <el-icon v-if="!componentCollapsed"><ArrowDown /></el-icon>-->
      <!--          <el-icon v-else><ArrowRight /></el-icon>-->
      <!--        </div>-->
      <!--        <div v-if="!componentCollapsed">-->
      <!--          <el-form-item label="上边距：">-->
      <!--            <div class="flex">-->
      <!--              <el-slider style="width: 70%" v-model="form.marginTop" />-->
      <!--              <el-input style="width: 30%; margin-left: 20px" v-model="form.marginTop">-->
      <!--                <template #append>px</template>-->
      <!--              </el-input>-->
      <!--            </div>-->
      <!--          </el-form-item>-->
      <!--          <el-form-item label="下边距：">-->
      <!--            <div class="flex">-->
      <!--              <el-slider style="width: 70%" v-model="form.marginBottom" />-->
      <!--              <el-input style="width: 30%; margin-left: 20px" v-model="form.marginBottom">-->
      <!--                <template #append>px</template>-->
      <!--              </el-input>-->
      <!--            </div>-->
      <!--          </el-form-item>-->
      <!--          <el-form-item label="左右边距：">-->
      <!--            <div class="flex">-->
      <!--              <el-slider style="width: 70%" v-model="form.marginHorizontal" />-->
      <!--              <el-input style="width: 30%; margin-left: 20px" v-model="form.marginHorizontal">-->
      <!--                <template #append>px</template>-->
      <!--              </el-input>-->
      <!--            </div>-->
      <!--          </el-form-item>-->
      <!--        </div>-->
      <!--      </div>-->
    </el-form>
  </div>
</template>

<script setup lang="ts">
  import { reactive, watch, toRaw, onMounted } from 'vue'
  import debounce from 'lodash/debounce'
  import { ArrowDown, ArrowRight } from '@element-plus/icons-vue'

  const props = defineProps({
    showBackgroundColor: {
      type: Boolean,
      default: true
    },
    contentData: {
      type: Object,
      default: () => ({})
    }
  })

  const emit = defineEmits(['updateStyle'])
  const contentCollapsed = ref(false)
  // const componentCollapsed = ref(false)

  interface FormData {
    bgType: string
    backgroundColor: string
    backgroundImg: string
    borderRadius: number

    // 合并字段（左右）
    marginHorizontal: number
    paddingHorizontal: number

    // 上下独立字段
    marginTop: number
    marginBottom: number
    paddingTop: number
    paddingBottom: number

    // 单边用于 emit
    marginLeft: number
    marginRight: number
    paddingLeft: number
    paddingRight: number

    fontSize?: number
    lineHeight?: number

    topRadiusProxy: number
    bottomRadiusProxy: number
  }

  const form = reactive<FormData>({
    bgType: '',
    backgroundColor: '',
    backgroundImg: '',
    borderRadius: 0,
    marginTop: 0,
    marginBottom: 0,
    marginLeft: 0,
    marginRight: 0,
    marginHorizontal: 0,
    paddingTop: 0,
    paddingBottom: 0,
    paddingLeft: 0,
    paddingRight: 0,
    paddingHorizontal: 0,
    topRadiusProxy: 0,
    bottomRadiusProxy: 0
  })

  // 同步左右边距、内边距
  watch(
    () => form.marginHorizontal,
    () => {
      form.marginLeft = form.marginRight = form.marginHorizontal
    }
  )
  watch(
    () => form.paddingHorizontal,
    () => {
      form.paddingLeft = form.paddingRight = form.paddingHorizontal
    }
  )

  const PX_FIELDS = [
    'marginTop',
    'marginRight',
    'marginBottom',
    'marginLeft',
    'paddingTop',
    'paddingRight',
    'paddingBottom',
    'paddingLeft',
    'borderRadius',
    'fontSize',
    'lineHeight',
    'topRadiusProxy',
    'bottomRadiusProxy'
  ]

  function formatFormForEmit(rawForm: Record<string, any>) {
    const result: Record<string, any> = {}
    for (const key in rawForm) {
      const val = rawForm[key]
      if (
        ['backgroundImg', 'backgroundColor'].includes(key) &&
        (val === '' || val === null || val === undefined)
      ) {
        continue
      }

      if (key === 'borderRadius') {
        if (
          ['category_nav', 'info_card', 'goods', 'nav_title', 'nav_link', 'article'].includes(
            props.contentData.type
          )
        ) {
          const top = rawForm.topRadiusProxy || 0
          const bottom = rawForm.bottomRadiusProxy || 0
          result.borderRadius = `${top}px ${top}px ${bottom}px ${bottom}px`
        } else {
          result.borderRadius = typeof val === 'number' ? `${val}px` : val
        }
        continue
      }

      if (PX_FIELDS.includes(key) && typeof val === 'number') {
        result[key] = val + 'px'
      } else {
        result[key] = val
      }
    }
    return result
  }

  function parseBorderRadiusShorthand(value: string | number | undefined | null): {
    top: number
    bottom: number
  } {
    if (typeof value === 'number') {
      return { top: value, bottom: value }
    }

    if (typeof value === 'string') {
      const parts = value.trim().split(/\s+/)
      const pxToNum = (v: string) => parseFloat(v.replace('px', '')) || 0

      if (parts.length === 1) {
        const val = pxToNum(parts[0])
        return { top: val, bottom: val }
      }
      if (parts.length === 2) {
        const [vertical] = parts
        const val = pxToNum(vertical)
        return { top: val, bottom: val }
      }
      if (parts.length === 3) {
        const [top, _, bottom] = parts
        return { top: pxToNum(top), bottom: pxToNum(bottom) }
      }
      if (parts.length >= 4) {
        const [top, , bottom] = parts
        return { top: pxToNum(top), bottom: pxToNum(bottom) }
      }
    }

    return { top: 0, bottom: 0 }
  }

  const emitFormUpdate = debounce(() => {
    const raw = toRaw(form)
    const formatted = formatFormForEmit(raw)
    emit('updateStyle', formatted)
  }, 300)

  watch(
    form,
    () => {
      emitFormUpdate()
    },
    { deep: true }
  )

  function parsePxValue(val: string | number | null | undefined): number {
    if (typeof val === 'string' && val.endsWith('px')) {
      return parseFloat(val)
    }
    if (typeof val === 'number') return val
    return 0
  }

  onMounted(() => {
    const s = props.contentData.style || {}

    form.marginTop = parsePxValue(s.marginTop)
    form.marginBottom = parsePxValue(s.marginBottom)
    form.marginLeft = parsePxValue(s.marginLeft)
    form.marginRight = parsePxValue(s.marginRight)
    form.paddingTop = parsePxValue(s.paddingTop)
    form.paddingBottom = parsePxValue(s.paddingBottom)
    form.paddingLeft = parsePxValue(s.paddingLeft)
    form.paddingRight = parsePxValue(s.paddingRight)
    form.borderRadius = parsePxValue(s.borderRadius)
    form.backgroundColor = s.backgroundColor || '#fff'

    form.marginHorizontal = (form.marginLeft + form.marginRight) / 2
    form.paddingHorizontal = (form.paddingLeft + form.paddingRight) / 2

    // 判断类型决定是否解析四值
    if (
      ['category_nav', 'info_card', 'goods', 'nav_title', 'nav_link', 'article'].includes(
        props.contentData.type
      )
    ) {
      const { top, bottom } = parseBorderRadiusShorthand(s.borderRadius)
      form.topRadiusProxy = top
      form.bottomRadiusProxy = bottom
    }
  })
</script>

<style scoped lang="scss">
  .component-style {
    width: 100%;
    box-sizing: border-box;
    margin-top: 40px;
    //padding: 20px;

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .title {
        font-size: 14px;
        font-weight: bold;
        color: black;
      }
    }
  }

  .flex {
    display: flex;
    justify-content: space-between;
    width: 100%;
    padding: 0 3px;
  }
</style>
